package com.cms.common.model.services.impl;

import com.cms.common.model.entity.Language;
import com.cms.common.model.repository.LanguageRepository;
import com.cms.common.model.services.LanguageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class LanguageServiceImpl implements LanguageService {

    @Autowired
    private LanguageRepository languageRepository;

    @Override
    public List<Language> findAll() {
        return languageRepository.findAll();
    }

    @Override
    public Language findByCode(String code) {
        return languageRepository.findByCode(code);
    }

    @Override
    public Optional<Language> findById(Long id) {
        return languageRepository.findById(id);
    }

    @Override
    public Language save(Language language) {
        if (language.getIsDefault()) {
            List<Language> defaultLanguages = languageRepository.findByIsDefault(true);
            if (!defaultLanguages.isEmpty()) {
                for (Language defaultLanguage : defaultLanguages) {
                    if (!defaultLanguage.getCode().equals(language.getCode())) {
                        defaultLanguage.setIsDefault(false);
                    }
                }
                languageRepository.saveAll(defaultLanguages);
            }

            language.setEnabled(true);
        }
        return languageRepository.save(language);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        // 检查是否为默认语言
        Optional<Language> language = languageRepository.findById(id);
        if (language.isPresent() && language.get().getIsDefault()) {
            throw new RuntimeException("默认语言不能删除");
        }
        languageRepository.deleteById(id);
    }

}
